import {
  copyLegendOpts, getLegendOpts,
  drawLabel, drawIcon, drawVal, drawLineRect, drawFillRect, drawStepRect,
  cacleOffset_x_y
} from './setting'

const defaultMes = {
  title: '',
  legend: []
}

export async function setLegend(ctx, mes = defaultMes, options = getLegendOpts()) {
  ctx.font = `${options.font_size}px serif`
  // ctx.fillStyle = options.font_color
  ctx.textBaseline = 'top'
  if (mes.title) {
    drawHeader(ctx, mes.title, options)
  }
  for (let i = 0; i < mes.legend.length; i++) {
    const item = mes.legend[i]

    switch (item.type) {
      case 'point':
        await drawPoint(ctx, item, options).then(res => { (options.pointer.x = 0) & (options.pointer.y += options.line_h) })
        break
      case 'line':
        drawLine(ctx, item, options)
        break
      case 'fill':
        if (item.texure) {
          await drawPoint(ctx, item, options).then(res => { (options.pointer.x = 0) & (options.pointer.y += options.line_h) })
        } else {
          drawFill(ctx, item, options)
        }
        break
      case 'step':
        drawStep(ctx, item, options)
        break
      default:
        break
    }
  }
}

/**
 * 绘制标题
 * @param {*} ctx
 * @param {*} title
 * @param {*} opts
 */
function drawHeader(ctx, title, opts) {
  ctx.save()

  ctx.font = `${opts.header_fontSize}px serif`
  const { width, height = opts.header_fontSize } = ctx.measureText(title)
  const { x, y } = cacleOffset_x_y(opts.canvas_w, opts.header_h, width, height, 'center') // 文字位置的左上角位置
  ctx.fillText(title, x, y)

  opts.pointer.y += opts.header_h // 更新指针位置

  ctx.restore()
}
function drawLine(ctx, mes, opts) {
  drawLabel(ctx, mes, opts) & (opts.pointer.x += opts.label_w)

  drawLineRect(ctx, mes, opts) & (opts.pointer.x = 0) & (opts.pointer.y += opts.line_h)
}
function drawFill(ctx, mes, opts) {
  drawLabel(ctx, mes, opts) & (opts.pointer.x += opts.label_w)
  drawFillRect(ctx, mes, opts) & (opts.pointer.x = 0) & (opts.pointer.y += opts.line_h)
}
function drawStep(ctx, mes, opts) {
  const steps = mes.steps

  for (let i = 0; i < steps.length; i++) {
    if (i === 0) {
      drawLabel(ctx, { label: mes.label }, opts) & (opts.pointer.x += opts.label_w)
      drawStepRect(ctx, steps[i], opts) & (opts.pointer.x += opts.icon_w)
      drawVal(ctx, steps[i], opts) & (opts.pointer.x = opts.label_w) & (opts.pointer.y += opts.line_h)
    } else {
      drawStepRect(ctx, steps[i], opts) & (opts.pointer.x += opts.icon_w)
      drawVal(ctx, steps[i], opts) & (opts.pointer.x = opts.label_w) & (opts.pointer.y += opts.line_h)
    }
  }
}
function drawPoint(ctx, mes, opts) {
  drawLabel(ctx, mes, opts) & (opts.pointer.x += opts.label_w)
  return drawIcon(ctx, mes, opts)
}
